//
//  StockAppDelegate.m
//  Stock
//
//  Created by blacksun on 11-6-5.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "StockAppDelegate.h"
#import "RootViewController.h"
#import "StoreKitContext.h"

#define LastRateDate    @"lastRateDate"
#define LastRateType    @"lastRateType"

@implementation StockAppDelegate


@synthesize window=_window;
@synthesize stockSections;
@synthesize stockAppService;
@synthesize pushToken;
@synthesize tabbarController;


@synthesize navigationController=_navigationController;


#pragma mark -Service Delegate
-(void)requestFinishedWithResult:(id)aResult andUserinfo:(NSDictionary *)aUserinfo{
    retryCount = 1;
    StockContext *context = [StockContext shareInstance];
    context.sections = aResult;
    NSString *action = [aUserinfo objectForKey:kASIHttpRequestUserinfoKey];
    if ([action isEqualToString:kStockAppServiceLogin] || [action isEqualToString:kStockAppServiceSignUp]) {
        if (self.pushToken && [StockContext shareInstance].userId) {
            [self.stockAppService sendPushToken:pushToken];
        }
    }
}
-(void)requestFinishedwithError:(NSError *)aError andUserinfo:(NSDictionary *)aUserinfo{
    NSString *action = [aUserinfo objectForKey:kASIHttpRequestUserinfoKey];
    if ([action isEqualToString:kStockAppServiceLogin] || [action isEqualToString:kStockAppServiceSignUp]) {
        if (retryCount<3) {
            [self updateRemoteData];
        }else{
            [[StockAppHelper shareInstance] showAlertViewWithMessage:@"访问网络超时"];
        }
        retryCount ++;
    }
}

-(void)updateRemoteData{
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    NSString *userId = [userDefault objectForKey:kUserIdInUserDefault];
    //NSLog(@"%@",userId);
    if (userId) {
        [stockAppService loginWithUserId:userId];
        [StockContext shareInstance].userId = userId;
    }else{
        [stockAppService signUp];
    }
    
}

- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController{
    int index = [tabbarController.viewControllers indexOfObject:viewController];
    if (index==0) {
        [StockContext shareInstance].workingStock = 0;
    }else if (index==1) {
        [StockContext shareInstance].workingStock = 4;
    }else if(index==4){
        [StockContext shareInstance].workingStock = 6;
    }
    self.navigationController = (UINavigationController *)viewController;
    return YES;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    
    [StoreKitContext shareInstance];
    retryCount = 0;
    
    
    [[StockAppHelper shareInstance] createTables];
    
    MyStock *mystock = [[[MyStock alloc] init] autorelease];
    ReadStatus *readStatus = [[[ReadStatus alloc] init] autorelease];
    [mystock save];
    [readStatus save];
    [mystock deleteObject];
    [readStatus deleteObject];
    
    
    NSString *path = [[CommonUtil shareInstance] pathOfResouceInMainBundle:@"kStocks.plist"];
    NSArray *tempStockSections = [[NSArray alloc] initWithContentsOfFile:path];
    self.stockSections = tempStockSections;
    [tempStockSections release];
    self.window.rootViewController = self.tabbarController;
    
    self.tabbarController.delegate = self;
    
    [self.window makeKeyAndVisible];
    
    self.stockAppService = [[[StockAppService alloc] initWithDelegate:self] autorelease];
    
    [self updateRemoteData];
    
    //NSLog(@"Registering for push notifications...");    
    [[UIApplication sharedApplication] 
     registerForRemoteNotificationTypes:
     (UIRemoteNotificationTypeAlert | 
      UIRemoteNotificationTypeBadge | 
      UIRemoteNotificationTypeSound)];
    application.applicationIconBadgeNumber = 0; //程序开启，设置UIRemoteNotificationTypeBadge标识为0
    
    
    [MobClick startWithAppkey:@"4ee0c4c15270157b94000009"];
    [MobClick checkUpdate];
    
    return YES;
}
-(void)gotoPurchase{
    //[self.tabbarController select:<#(id)#>]
}

- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { 
    NSString *token = [NSString stringWithFormat:@"%@",deviceToken];
    token = [token stringByReplacingOccurrencesOfString:@"<" withString:@""];
    token = [token stringByReplacingOccurrencesOfString:@">" withString:@""];
    self.pushToken = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSLog(@"token=%@",pushToken);
    if ([StockContext shareInstance].userId) {
        [self.stockAppService sendPushToken:pushToken];
    }
}

- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err { 
    
    NSString *str = [NSString stringWithFormat: @"Error: %@", err];
    NSLog(@"%@",str);    
    
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    /*if ([[userInfo objectForKey:@"type"] isEqualToString:@"StockMonitor"]) {
        NSString *stockId = [userInfo objectForKey:@"stockId"];
        int direction = [[userInfo objectForKey:@"direction"] intValue];
        StockRadar *radar = [StockRadar findByStockId:stockId andType:direction];
        if (!radar.repeat) {
            radar.status = 1;
        }
        radar.lastDate = [NSDate dateWithTimeIntervalSinceNow:1];
        [radar save];
    }
    for (NSString* key in userInfo) {
        NSLog(@"key: %@, value: %@", key, [userInfo objectForKey:key]);
    } */   
    
}



- (void)applicationWillResignActive:(UIApplication *)application{
    
}

- (void)applicationDidEnterBackground:(UIApplication *)application{
    [self.stockAppService logout];
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    retryCount=0;
    [self updateRemoteData];
    [StockContext shareInstance].needDisplayOpnition = YES;
    UINavigationController *navigationController = (UINavigationController *)self.tabbarController.selectedViewController;
    if(self.tabbarController.selectedIndex!=3){
        [navigationController popToRootViewControllerAnimated:NO];
    }
    [self.tabbarController.selectedViewController viewWillAppear:YES];
    
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    if ([self needShowRateAlert]) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"给我们评分" message:@"如果您喜欢股市随身听，请在App Store为它打分。谢谢！" delegate:self cancelButtonTitle:@"以后再说" otherButtonTitles:@"现在就去", nil];
        [alertView show];
        [alertView release];
    }
}
-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex{
    if (buttonIndex==1) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:AppReViewURL]];
    }
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    [userDefault setObject:[NSDate date] forKey:LastRateDate];
    [userDefault setInteger:buttonIndex forKey:LastRateType];
    [userDefault synchronize];
}
-(BOOL)needShowRateAlert{
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    NSDate *lastDate = [userDefault objectForKey:LastRateDate];
    if (lastDate==nil) {
        [userDefault setObject:[NSDate date] forKey:LastRateDate];
        [userDefault setInteger:2 forKey:LastRateType];
        [userDefault synchronize];
        return NO;
    }
    BOOL needShow = NO;
    NSInteger lastRateType = [userDefault integerForKey:LastRateType];
    NSDate *currentDate = [NSDate date];
    switch (lastRateType) {
        case 0:
            needShow = [currentDate timeIntervalSinceDate:lastDate]>7*24*3600;
            break;
        case 1:
            needShow = [currentDate timeIntervalSinceDate:lastDate]>30*24*3600;
            break;
        case 2:
            needShow = [currentDate timeIntervalSinceDate:lastDate]>3*24*3600;
            break;
        default:
            break;
    }
    return needShow;
}
- (void)applicationWillTerminate:(UIApplication *)application
{
}


- (void)dealloc
{
    [_window release];
    [_navigationController release];
    [stockSections release];
    [stockAppService cancleAllRequest];
    [stockAppService release];
    [pushToken release];
    [tabbarController release];
    [super dealloc];
}

@end